/*
 * layui 扩展侧边菜单栏组件
 * Autor：maliang
 * Date : 17-08-15
 */

//配置sidemenu
//sidemenu.set({ elem: '#admin-navbar-side', url: 'datas/nav.json' });
//渲染sidemenu
//sidemenu.render();
//监听点击事件
//sidemenu.on('click(side)', function(data) { });

layui.define(['element', 'layer'], function(exports) {
  var $ = layui.jquery,
    layer = layui.layer,
    element = layui.element,
    cacheName = 'sidemenu';

  var Sidemenu = function() {
    /**
     *  默认配置
     */
    this.config = {
      elem: undefined, //容器
      data: undefined, //数据源
      url: undefined, //数据源地址
      type: 'GET', //读取方式
      cached: false //是否使用缓存
    };
    this.v = '0.0.1';
  }
  var sidemenu = new Sidemenu();

  var obj = {
    /**
     * 渲染界面
     */
    render: function() {
      var _that = sidemenu;
      var _config = _that.config;
      if (typeof(_config.elem) !== 'string' && typeof(_config.elem) !== 'object') {
        layer.alert('Sidemenu error: elem参数未定义或设置出错.', '出错');
      }
      var $container;
      if (typeof(_config.elem) === 'string') {
        $container = $('' + _config.elem + '');
      }
      if (typeof(_config.elem) === 'object') {
        $container = _config.elem;
      }
      if ($container.length === 0) {
        layer.alert('Sidemenu error:找不到elem参数配置的容器，请检查.', '出错');
      }
      if (_config.data === undefined && _config.url === undefined) {
        layer.alert('Sidemenu error:请为Navbar配置数据源.', '出错')
      }
      if (_config.data !== undefined && typeof(_config.data) === 'object') {
        var html = getHtml(_config.data);
        $container.html(html);
        element.init();
        _that.config.elem = $container;
      } else {
        if (_config.cached) {
          var cacheSidemenu = layui.data(cacheName);
          if (cacheSidemenu.sidemenu === undefined) {
            $.ajax({
              type: _config.type,
              url: _config.url,
              async: false, //_config.async,
              dataType: 'json',
              success: function(result, status, xhr) {
                //添加缓存
                layui.data(cacheName, {
                  key: 'sidemenu',
                  value: result
                });
                var html = getHtml(result);
                $container.html(html);
                element.init();
              },
              error: function(xhr, status, error) {
                layer.alert('Sidemenu error:' + error);
              },
              complete: function(xhr, status) {
                _that.config.elem = $container;
              }
            });
          } else {
            var html = getHtml(cacheSidemenu.sidemenu);
            $container.html(html);
            element.init();
            _that.config.elem = $container;
          }
        } else {
          //清空缓存
          layui.data(cacheName, null);
          
          $.ajax({
            type: _config.type,
            url: _config.url,
            async: false, //_config.async,
            dataType: 'text',
            success: function(result, status, xhr) {
              var rsp = JSON.parse(result);	
              var html = getHtml(rsp);
              $container.html(html);
              element.init();
            },
            error: function(xhr, status, error) {
              layer.alert('Sidemenu error:' + error);
            },
            complete: function(xhr, status) {
              _that.config.elem = $container;
            }
          });
        }
      }
      return _that;
    },
    /**
     * 配置Sidemenu
     */
    cnf: function(options) {
      var that = sidemenu;
      //采用递归方式合并两个对象，并修改第一个对象。
      $.extend(that.config, options);
      return that;
    },

    /**
     * 显示tips
     */
    showTips: function() {
      var li = $(".layui-side-scroll").find("li");
      var dd = $(".layui-side-scroll").find("dd");
      var systemTigle=$(".system-title");

      li.hover(function() {
        var title = $(this).find("a:first").text();
        /*layer.tips(title, this, {
          tips: 2,
          time: 1500
        });*/
      });


      dd.hover(function() {
        var title = $(this).find("a").text();
       /* layer.tips(title, this, {
          tips: 2,
          time: 1500
        });*/
      });

      systemTigle.hover(function() {
        var title = $(this).text();
        /*layer.tips(title, this, {
          tips: 2,
          time: 1500
        });*/
      });
    },

    on: function(events, callback) {
      var that = sidemenu;
      var _con = that.config.elem;
      if (typeof(events) !== 'string') {
        layer.alert('Sidemenu error:事件名配置出错.', '出错');
      }
      var lIndex = events.indexOf('(');
      var eventName = events.substr(0, lIndex);
      var filter = events.substring(lIndex + 1, events.indexOf(')'));
      if (eventName === 'click') {
    	  
        if (_con.attr('lay-filter') !== undefined) {
          _con.children('ul').find('li').each(function() {
            var $this = $(this);
            if ($this.find('dl').length > 0) {
              var $dd = $this.find('dd').each(function() {
                $(this).on('click', function() {
                  var $a = $(this).children('a');
                  var href = $a.data('url');
                  var icon = $a.children('i').text();
                  var title = $a.children('cite').text();
                  var data = {
                    elem: $a,
                    field: {
                      href: href,
                      icon: icon,
                      title: title
                    }
                  }
                  callback(data);
                });
              });
            } else {
              $this.on('click', function() {
                var $a = $this.children('a');
                var href = $a.data('url');
                var icon = $a.children('i').attr('class');
                var title = $a.children('cite').text();
                var data = {
                  elem: $a,
                  field: {
                    href: href,
                    icon: icon,
                    title: title
                  }
                }
                callback(data);
              });
            }
          });
        }
      }
    }
  };
  exports('sidemenu', obj);
});

/**
 * 获取html字符串
 */
function getHtml(menuData) {
  var ulHtml = "";
  // var k=1;
  for (var k = 0; k < menuData.length; k++) {
    var data = menuData[k].children;
    ulHtml += '<div class="system-title"><i class="' + menuData[k].icon + '"></i>' + menuData[k].title + '</div>';
    ulHtml += '<ul class="layui-nav layui-nav-tree" lay-filter="test">';

    for (var i = 0; i < data.length; i++) {
      if (data[i].spread) {
        ulHtml += '<li class="layui-nav-item layui-nav-itemed">';
      } else {
        ulHtml += '<li class="layui-nav-item">';
      }
      if (data[i].children !== undefined && data[i].children.length > 0) {
        ulHtml += '<a href="javascript:;">'
        if (data[i].icon !== undefined && data[i].icon !== '') {
          ulHtml += '<i class="' + data[i].icon + '"></i>';
        }
        ulHtml += '<span>'+data[i].title+'</span>';
        ulHtml += '</a>';
        ulHtml += '<dl class="layui-nav-child">'
        for (var j = 0; j < data[i].children.length; j++) {
          ulHtml += '<dd>';
          ulHtml += '<a href="javascript:;" data-url="' + data[i].children[j].href + '">';
          if (data[i].children[j].icon !== undefined && data[i].children[j].icon !== '') {
            if (data[i].icon !== undefined && data[i].icon !== '') {
              ulHtml += '<i class="' + data[i].children[j].icon + '"></i>';
            }
          }
          ulHtml += '<span>'+data[i].children[j].title+'</span>';
          ulHtml += '</a>';
          ulHtml += '</dd>';
        }
        ulHtml += '</dl>';
      } else {
        var dataUrl = (data[i].href !== undefined && data[i].href !== '') ? 'data-url="' + data[i].href + '"' : '';
        ulHtml += '<a href="javascript:;" ' + dataUrl + '>';
        if (data[i].icon !== undefined && data[i].icon !== '') {
          if (data[i].icon !== undefined && data[i].icon !== '') {
            ulHtml += '<i class="' + data[i].icon + '"></i>';
          }
        }
        ulHtml += '<span>'+data[i].title+'</span>';
        ulHtml += '</a>';
      }
      ulHtml += '</li>';
    }
    ulHtml += '</ul>';
  }
  return ulHtml;
}
